import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login'
import Todolist from '@/components/Todolist'

Vue.use(Router)
// export default
const vueRouter = new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/todolist',
      name: 'Todolist',
      component: Todolist
    },
    {
      path: '*',
      redirect: '/'
    }
  ]
})

vueRouter.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('todolist-token')
  if (to.path === '/') { // 如果是跳转到登录页的
    // console.log(to.path, (token !== 'null' && token !== null))
    if (token !== 'null' && token !== null) {
      next('/todolist') // 如果有token就转向todolist不返回登录页
    }
    next() // 否则跳转回登录页
  } else {
    if (token !== 'null' && token !== null) {
      Vue.prototype.$ajax.defaults.headers.common['Authorization'] = 'Bearer ' + token
      next() // 如果有token就正常转向
    } else {
      next('/') // 否则跳转回登录页
    }
  }
})

export default vueRouter
